package com.kgc.itrip.controller;

import com.kgc.itrip.common.Constants;
import com.kgc.itrip.common.DtoUtil;
import com.kgc.itrip.dto.Dto;
import com.kgc.itrip.exception.TokenValidationFailedException;
import com.kgc.itrip.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 提供客户端置换token的控制器
 *
 * @author lrg on 2021/3/16
 * @since 1.0.0
 */
@Api(value = "提供客户端置换token的控制器")
@RestController
@RequestMapping("/api")
public class TokenController {
    @Resource
    private TokenService tokenService;

    @ApiOperation(value = "提供客户端置换token操作，服务器需要获取客户端header中的token串",
            httpMethod = "POST",notes = "提供客户端置换token操作，服务器需要获取客户端header中的token串",
            protocols = "http",produces = "application/json;charset=UTF-8",
            consumes = "application/json")
    @PostMapping(value="/retoken")
    public Dto reToken(HttpServletRequest request) throws TokenValidationFailedException, ParseException {
        Map<String,String> tokenInfo = new HashMap<>();
        //获取token
        String token = request.getHeader("token");
        //获取agent
        String agent = request.getHeader("User-Agent");
        String newToken = tokenService.replaceToken(agent,token);
        tokenInfo.put("token",newToken);
        tokenInfo.put("ticket","");
        String[] tokenDetails = token.split("-");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        //获取token生成时间
        Date TokenGenTime = formatter.parse(tokenDetails[3]);
        tokenInfo.put("genTime",String.valueOf(TokenGenTime.getTime()));
        //设置返回结果中的token的生成时间
        tokenInfo.put("expTime",String.valueOf(TokenGenTime.getTime()+Constants.SESSION_TIMEOUT * 1000));
        return DtoUtil.returnDataSuccess(tokenInfo);
    }
}
